package hammersmith.local.persistence;

import hammersmith.local.management.ShopManagement;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * DBHandler-Klasse zum Speichern des Shops
 * 
 * @author hammersmith
 *
 */
public class DBHandler {

	private File file;

	public DBHandler() {
		this.file = new File("db/20Bucks-Shop_new.xml");
	}

	/**
	 * Methode zum speichern des Shops
	 * 
	 * @param shop
	 */
	public void saveShop(ShopManagement shop) {
		XMLEncoder xmlEncoder;

		try {
			//Datei zuweisen
			xmlEncoder = new XMLEncoder(new FileOutputStream(file));
			//Shop serialisieren -> in die XML-Datei speichern
			xmlEncoder.writeObject(shop);
			//Stream leeren!
			xmlEncoder.flush();
			//Stream schliessen
			xmlEncoder.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Methode zum laden (deserialiseren) des Shops aus der XML-Datei
	 * 
	 * @return
	 */
	public ShopManagement loadShop() {
		XMLDecoder xmlDecoder;

		try {
			//Datei zuweisen
			xmlDecoder = new XMLDecoder(new FileInputStream(file));
			//Shop deserialisieren -> aus XML-Datei lesen und im shopManager-Objekt speichern
			ShopManagement shopManager = (ShopManagement) xmlDecoder
					.readObject();
			//Stream schliessen
			xmlDecoder.close();

			return shopManager;
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("Leider keine Shoprueckgabe moeglich!");
			return null;
		}
	}
	
	
}
